package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * TODO
 *
 * @Description
 * @Author jresm骏
 * @Date 2022/12/8 17:19
 **/
@Component
public class StocklimitRoutePredicateFactory extends AbstractRoutePredicateFactory<StocklimitRoutePredicateFactory.Config> {
    public StocklimitRoutePredicateFactory() {
        //确保抛出的是PidlimitRoutePredicateFactory里面的Config的class对象
        super(Config.class);
    }
    /**
     * - Pidlimit=1,3  需要截取1赋值给minPid，3赋值给maxPid
     * ChangeLog : 1. 创建 (22/12/08/0008 16:44 [马宇航]);
     *
     * @return java.util.List<java.lang.String>
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid","maxPid","minStock","maxStock");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();
                String[] split = path.split("/");
                String pidString = split[split.length - 2];
                String stockString = split[split.length - 1];
                int pid = Integer.parseInt(pidString);
                int stock = Integer.parseInt(stockString);
                if(config.getMinPid()<=pid&&pid<=config.getMaxPid()&&stock<=config.getMaxStock()&&stock>=config.getMinStock()){
                    return true;
                }else {
                    return false;
                }
            }
        };
    }

/**
 * TODO
 *
 * @Description  静态内部类：它和 写外面是一样的！
 * @Author jresm骏
 * @Date 2022/12/8 17:19
 */
    public static class Config{
        int minPid;
        int maxPid;
        int minStock;
        int maxStock;

    public int getMinPid() {
        return minPid;
    }

    public void setMinPid(int minPid) {
        this.minPid = minPid;
    }

    public int getMaxPid() {
        return maxPid;
    }

    public void setMaxPid(int maxPid) {
        this.maxPid = maxPid;
    }

    public int getMinStock() {
        return minStock;
    }

    public void setMinStock(int minStock) {
        this.minStock = minStock;
    }

    public int getMaxStock() {
        return maxStock;
    }

    public void setMaxStock(int maxStock) {
        this.maxStock = maxStock;
    }
}
}
